var IntldialingAssistant = Class.create({

    initialize: function(args) {
		this.countries = [];
		
		InternationalDialingSettings.each(function(region) {
			this.countries.push({
				label: String(region.value.name),
				id: region.key,
				checkmark: (args && args.regionId === region.key ? "checkmark" : "" )
			});
		}, this)
		
		this.countries.sort(this.compareCountry);
		
		this.regionModel = {
			"items": this.countries
		}
	},
	
	setup: function() {
		this.controller.setupWidget('regionList', {
			itemTemplate:'intldialing/listitem',
			listTemplate:'intldialing/listcontainer',
			filterFunction: this.regionFilter.bind(this)
		}, this.regionModel); 
		
    	$('regionList').observe(Mojo.Event.listTap, this.regionSet.bindAsEventListener(this));
	},
	
	regionFilter: function(filterString, listWidget, offset, count) {
		var matching, lowerFilter;
		if (filterString) {
			lowerFilter = filterString.toLocaleLowerCase();
			function matchesName (country) {
				return country.label.toLocaleLowerCase().startsWith(lowerFilter);
			}
			matching = this.countries.findAll(matchesName);
		} else {
			matching = this.countries;
		}
		this.regionModel.items = matching;			
		listWidget.mojo.setLength(matching.length);
		listWidget.mojo.setCount(matching.length);
		listWidget.mojo.noticeUpdatedItems(0, matching);
	},
	
	regionSet: function(event) {
		var id = event.item.id;
		SystemService.setSystemPreferencesService("phoneInternationalDialingActive", true);
		SystemService.setSystemPreferencesService("phoneInternationalDialingRegionId", id);
		this.controller.stageController.popScene({type:"refresh"});
	},
	
	compareCountry: function(a,b) {
		// extra "" is to stringify the labels; the localization objects don't 
		// have toLowerCase right now
		var nameA = (a.label + "").toLocaleLowerCase();
		var nameB = (b.label + "").toLocaleLowerCase();
		return nameA.localeCompare(nameB);
	},
});
